/**
 * XDevice Raft 集群成员管理实现
 * 
 * 实现动态成员管理、热备节点、故障自愈等功能
 */

#include <xdevice/raft_membership.h>
#include <xdevice/raft.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <time.h>
#include <unistd.h>
#include <sys/time.h>

#define _POSIX_C_SOURCE 200809L

/* 全局集群配置 */
static raft_cluster_config_t g_cluster_config = {0};
static raft_auto_healing_config_t g_auto_healing_config = {0};
static raft_member_change_callback_t g_change_callback = NULL;
static pthread_mutex_t g_membership_lock;
static pthread_t g_health_monitor_thread;
static bool g_membership_initialized = false;
static bool g_health_monitoring_active = false;

/* 内部辅助函数 */
static uint64_t get_current_time_ms(void) {
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return tv.tv_sec * 1000ULL + tv.tv_usec / 1000;
}

static void log_membership_event(const char* event, int node_id, const char* details) {
    printf("[MEMBERSHIP] %s: Node %d - %s\n", event, node_id, details ? details : "");
}

static int find_active_member_index(int node_id) {
    for (int i = 0; i < g_cluster_config.active_count; i++) {
        if (g_cluster_config.active_members[i].node_id == node_id) {
            return i;
        }
    }
    return -1;
}

static int find_standby_node_index(int node_id) {
    for (int i = 0; i < g_cluster_config.standby_count; i++) {
        if (g_cluster_config.standby_nodes[i].node_id == node_id) {
            return i;
        }
    }
    return -1;
}

/* 计算当前法定人数 */
static int calculate_quorum_size(void) {
    if (g_cluster_config.in_joint_consensus) {
        // 联合一致性：需要在新旧配置中都获得多数
        // 简化实现：使用更严格的要求
        return (g_cluster_config.active_count / 2) + 1;
    } else {
        return (g_cluster_config.active_count / 2) + 1;
    }
}

/* 健康监控线程 */
static void* health_monitor_thread(void* arg) {
    (void)arg;
    
    log_membership_event("MONITOR_START", -1, "Health monitoring started");
    
    while (g_health_monitoring_active) {
        pthread_mutex_lock(&g_membership_lock);
        
        uint64_t current_time = get_current_time_ms();
        bool cluster_changed = false;
        
        // 检查活跃成员健康状态
        for (int i = 0; i < g_cluster_config.active_count; i++) {
            raft_member_info_t* member = &g_cluster_config.active_members[i];
            
            // 检查心跳超时
            if (current_time - member->last_heartbeat_time > 
                g_auto_healing_config.recovery_timeout_ms) {
                
                if (member->status == RAFT_MEMBER_ACTIVE) {
                    member->status = RAFT_MEMBER_FAILED;
                    member->failure_count++;
                    member->health_score = 0.0;
                    
                    log_membership_event("MEMBER_FAILED", member->node_id, 
                                       "Heartbeat timeout detected");
                    
                    if (g_change_callback) {
                        g_change_callback(RAFT_CONFIG_REMOVE_MEMBER, member, 
                                        "Heartbeat timeout");
                    }
                    
                    cluster_changed = true;
                    
                    // 触发自动修复
                    if (g_auto_healing_config.enable_auto_healing) {
                        raft_handle_member_failure(member->node_id);
                    }
                }
            }
            
            // 健康评分检查
            if (member->health_score < g_auto_healing_config.min_health_score &&
                member->status == RAFT_MEMBER_ACTIVE) {
                
                log_membership_event("MEMBER_DEGRADED", member->node_id, 
                                   "Health score below threshold");
                
                // 如果有热备节点，考虑替换
                if (g_auto_healing_config.enable_standby_promotion && 
                    g_cluster_config.standby_count > 0) {
                    
                    // 找到最健康的热备节点
                    int best_standby = -1;
                    double best_score = 0.0;
                    
                    for (int j = 0; j < g_cluster_config.standby_count; j++) {
                        if (g_cluster_config.standby_nodes[j].health_score > best_score) {
                            best_score = g_cluster_config.standby_nodes[j].health_score;
                            best_standby = j;
                        }
                    }
                    
                    if (best_standby >= 0 && best_score > 0.8) {
                        log_membership_event("AUTO_REPLACEMENT", member->node_id, 
                                           "Replacing with healthy standby");
                        
                        // 执行替换（在锁外执行实际操作）
                        pthread_mutex_unlock(&g_membership_lock);
                        raft_replace_member(member->node_id, 
                                          &g_cluster_config.standby_nodes[best_standby]);
                        pthread_mutex_lock(&g_membership_lock);
                        
                        cluster_changed = true;
                    }
                }
            }
        }
        
        // 检查JOINING状态的成员是否可以转换为ACTIVE
        for (int i = 0; i < g_cluster_config.active_count; i++) {
            raft_member_info_t* member = &g_cluster_config.active_members[i];
            
            if (member->status == RAFT_MEMBER_JOINING) {
                // 检查加入条件：
                // 1. 心跳正常（最近收到心跳）
                // 2. 加入时间超过最小等待时间
                // 3. 日志基本同步（简化检查）
                
                uint64_t join_duration = current_time - member->last_heartbeat_time;
                bool heartbeat_ok = join_duration < g_auto_healing_config.recovery_timeout_ms;
                bool min_time_passed = (current_time - member->last_heartbeat_time) > 1000; // 1秒最小等待
                
                if (heartbeat_ok && min_time_passed) {
                    // 自动将JOINING状态转换为ACTIVE
                    member->status = RAFT_MEMBER_ACTIVE;
                    member->health_score = 1.0;
                    
                    log_membership_event("MEMBER_ACTIVATED", member->node_id, 
                                       "Automatically promoted from JOINING to ACTIVE");
                    
                    if (g_change_callback) {
                        g_change_callback(RAFT_CONFIG_MEMBER_STATUS_CHANGE, member, 
                                        "Auto-promoted to active");
                    }
                    
                    cluster_changed = true;
                }
            }
        }
        
        // 更新配置版本
        if (cluster_changed) {
            g_cluster_config.config_version++;
        }
        
        pthread_mutex_unlock(&g_membership_lock);
        
        // 休眠到下次检查
        usleep(g_auto_healing_config.health_check_interval * 1000);
    }
    
    log_membership_event("MONITOR_STOP", -1, "Health monitoring stopped");
    return NULL;
}

/* ========== 公共API实现 ========== */

int raft_membership_init(void) {
    if (g_membership_initialized) {
        return 0;
    }
    
    // 初始化互斥锁
    if (pthread_mutex_init(&g_membership_lock, NULL) != 0) {
        return -1;
    }
    
    // 初始化配置
    memset(&g_cluster_config, 0, sizeof(g_cluster_config));
    g_cluster_config.config_version = 1;
    g_cluster_config.in_joint_consensus = false;
    
    // 设置默认自动修复配置
    g_auto_healing_config.enable_auto_healing = true;
    g_auto_healing_config.failure_threshold = 3;
    g_auto_healing_config.recovery_timeout_ms = 5000;
    g_auto_healing_config.health_check_interval = 1000;
    g_auto_healing_config.enable_standby_promotion = true;
    g_auto_healing_config.min_health_score = 0.6;
    
    // 启动健康监控线程
    g_health_monitoring_active = true;
    if (pthread_create(&g_health_monitor_thread, NULL, health_monitor_thread, NULL) != 0) {
        pthread_mutex_destroy(&g_membership_lock);
        return -1;
    }
    
    g_membership_initialized = true;
    log_membership_event("INIT", -1, "Membership management initialized");
    
    return 0;
}

void raft_membership_cleanup(void) {
    if (!g_membership_initialized) {
        return;
    }
    
    // 停止健康监控
    g_health_monitoring_active = false;
    pthread_join(g_health_monitor_thread, NULL);
    
    // 清理资源
    pthread_mutex_destroy(&g_membership_lock);
    
    g_membership_initialized = false;
    log_membership_event("CLEANUP", -1, "Membership management cleaned up");
}

int raft_get_cluster_config(raft_cluster_config_t* config) {
    if (!config || !g_membership_initialized) {
        return -1;
    }
    
    pthread_mutex_lock(&g_membership_lock);
    memcpy(config, &g_cluster_config, sizeof(raft_cluster_config_t));
    pthread_mutex_unlock(&g_membership_lock);
    
    return 0;
}

int raft_add_member(const raft_member_info_t* member_info) {
    if (!member_info || !g_membership_initialized) {
        return -1;
    }
    
    pthread_mutex_lock(&g_membership_lock);
    
    // 检查是否已存在
    if (find_active_member_index(member_info->node_id) >= 0) {
        pthread_mutex_unlock(&g_membership_lock);
        return -2; // 已存在
    }
    
    // 检查容量
    if (g_cluster_config.active_count >= RAFT_MAX_CLUSTER_MEMBERS) {
        pthread_mutex_unlock(&g_membership_lock);
        return -3; // 容量已满
    }
    
    // 添加新成员
    raft_member_info_t* new_member = &g_cluster_config.active_members[g_cluster_config.active_count];
    memcpy(new_member, member_info, sizeof(raft_member_info_t));
    new_member->status = RAFT_MEMBER_JOINING;
    new_member->join_term = raft_cluster_get_term();
    new_member->last_heartbeat_time = get_current_time_ms();
    new_member->failure_count = 0;
    new_member->health_score = 1.0;
    
    g_cluster_config.active_count++;
    g_cluster_config.config_version++;
    
    // 简化实现：在单节点或测试环境中，立即激活成员
    // 在生产环境中，这应该等待日志同步完成
    if (g_cluster_config.active_count <= 1 || 
        g_auto_healing_config.enable_auto_healing) {
        new_member->status = RAFT_MEMBER_ACTIVE;
        log_membership_event("MEMBER_AUTO_ACTIVATED", member_info->node_id, 
                           "Member auto-activated (single node or test mode)");
    }
    
    pthread_mutex_unlock(&g_membership_lock);
    
    log_membership_event("MEMBER_ADDED", member_info->node_id, "New member added to cluster");
    
    if (g_change_callback) {
        g_change_callback(RAFT_CONFIG_ADD_MEMBER, new_member, "Manual addition");
    }
    
    return 0;
}

int raft_remove_member(int node_id, const char* reason) {
    if (!g_membership_initialized) {
        return -1;
    }
    
    pthread_mutex_lock(&g_membership_lock);
    
    int index = find_active_member_index(node_id);
    if (index < 0) {
        pthread_mutex_unlock(&g_membership_lock);
        return -2; // 节点不存在
    }
    
    raft_member_info_t removed_member = g_cluster_config.active_members[index];
    
    // 移除成员（移动数组元素）
    for (int i = index; i < g_cluster_config.active_count - 1; i++) {
        g_cluster_config.active_members[i] = g_cluster_config.active_members[i + 1];
    }
    g_cluster_config.active_count--;
    g_cluster_config.config_version++;
    
    pthread_mutex_unlock(&g_membership_lock);
    
    log_membership_event("MEMBER_REMOVED", node_id, reason ? reason : "Manual removal");
    
    if (g_change_callback) {
        g_change_callback(RAFT_CONFIG_REMOVE_MEMBER, &removed_member, reason);
    }
    
    return 0;
}

int raft_add_standby_node(const raft_member_info_t* standby_info) {
    if (!standby_info || !g_membership_initialized) {
        return -1;
    }
    
    pthread_mutex_lock(&g_membership_lock);
    
    // 检查容量
    if (g_cluster_config.standby_count >= RAFT_MAX_STANDBY_NODES) {
        pthread_mutex_unlock(&g_membership_lock);
        return -3; // 容量已满
    }
    
    // 检查是否已存在
    if (find_standby_node_index(standby_info->node_id) >= 0) {
        pthread_mutex_unlock(&g_membership_lock);
        return -2; // 已存在
    }
    
    // 添加热备节点
    raft_member_info_t* standby = &g_cluster_config.standby_nodes[g_cluster_config.standby_count];
    memcpy(standby, standby_info, sizeof(raft_member_info_t));
    standby->status = RAFT_MEMBER_STANDBY;
    standby->is_voting_member = false; // 热备节点没有投票权
    standby->last_heartbeat_time = get_current_time_ms();
    standby->failure_count = 0;
    standby->health_score = 1.0;
    
    g_cluster_config.standby_count++;
    g_cluster_config.config_version++;
    
    pthread_mutex_unlock(&g_membership_lock);
    
    log_membership_event("STANDBY_ADDED", standby_info->node_id, "New standby node added");
    
    return 0;
}

int raft_promote_standby_to_active(int standby_node_id) {
    if (!g_membership_initialized) {
        return -1;
    }
    
    pthread_mutex_lock(&g_membership_lock);
    
    int standby_index = find_standby_node_index(standby_node_id);
    if (standby_index < 0) {
        pthread_mutex_unlock(&g_membership_lock);
        return -2; // 热备节点不存在
    }
    
    // 检查活跃成员容量
    if (g_cluster_config.active_count >= RAFT_MAX_CLUSTER_MEMBERS) {
        pthread_mutex_unlock(&g_membership_lock);
        return -3; // 活跃成员已满
    }
    
    // 移动节点从热备到活跃
    raft_member_info_t promoted_member = g_cluster_config.standby_nodes[standby_index];
    promoted_member.status = RAFT_MEMBER_ACTIVE;
    promoted_member.is_voting_member = true;
    promoted_member.join_term = raft_cluster_get_term();
    
    // 添加到活跃成员
    g_cluster_config.active_members[g_cluster_config.active_count] = promoted_member;
    g_cluster_config.active_count++;
    
    // 从热备列表移除
    for (int i = standby_index; i < g_cluster_config.standby_count - 1; i++) {
        g_cluster_config.standby_nodes[i] = g_cluster_config.standby_nodes[i + 1];
    }
    g_cluster_config.standby_count--;
    
    g_cluster_config.config_version++;
    
    pthread_mutex_unlock(&g_membership_lock);
    
    log_membership_event("STANDBY_PROMOTED", standby_node_id, "Standby promoted to active member");
    
    if (g_change_callback) {
        g_change_callback(RAFT_CONFIG_PROMOTE_STANDBY, &promoted_member, "Standby promotion");
    }
    
    return 0;
}

int raft_handle_member_failure(int node_id) {
    if (!g_membership_initialized) {
        return -1;
    }
    
    pthread_mutex_lock(&g_membership_lock);
    
    int index = find_active_member_index(node_id);
    if (index < 0) {
        pthread_mutex_unlock(&g_membership_lock);
        return -2; // 节点不存在
    }
    
    raft_member_info_t* member = &g_cluster_config.active_members[index];
    member->status = RAFT_MEMBER_FAILED;
    member->failure_count++;
    member->health_score = 0.0;
    
    bool should_remove = (member->failure_count >= g_auto_healing_config.failure_threshold);
    bool has_standby = (g_cluster_config.standby_count > 0);
    
    pthread_mutex_unlock(&g_membership_lock);
    
    log_membership_event("FAILURE_HANDLED", node_id, "Member failure processed");
    
    // 如果故障次数超过阈值，尝试自动修复
    if (should_remove && g_auto_healing_config.enable_auto_healing) {
        if (has_standby && g_auto_healing_config.enable_standby_promotion) {
            // 找到最佳热备节点进行替换
            raft_member_info_t best_standby = {0};
            double best_score = 0.0;
            int best_index = -1;
            
            pthread_mutex_lock(&g_membership_lock);
            for (int i = 0; i < g_cluster_config.standby_count; i++) {
                if (g_cluster_config.standby_nodes[i].health_score > best_score) {
                    best_score = g_cluster_config.standby_nodes[i].health_score;
                    best_standby = g_cluster_config.standby_nodes[i];
                    best_index = i;
                }
            }
            pthread_mutex_unlock(&g_membership_lock);
            
            if (best_index >= 0 && best_score > 0.7) {
                log_membership_event("AUTO_REPLACE", node_id, "Replacing failed member with standby");
                raft_replace_member(node_id, &best_standby);
            }
        } else {
            // 没有热备节点，直接移除故障成员
            log_membership_event("AUTO_REMOVE", node_id, "Removing failed member");
            raft_remove_member(node_id, "Automatic removal due to repeated failures");
        }
    }
    
    return 0;
}

int raft_replace_member(int old_node_id, const raft_member_info_t* new_member) {
    if (!new_member || !g_membership_initialized) {
        return -1;
    }
    
    pthread_mutex_lock(&g_membership_lock);
    
    int old_index = find_active_member_index(old_node_id);
    if (old_index < 0) {
        pthread_mutex_unlock(&g_membership_lock);
        return -2; // 旧节点不存在
    }
    
    // 保存旧成员信息用于回调
    raft_member_info_t old_member = g_cluster_config.active_members[old_index];
    
    // 替换成员
    memcpy(&g_cluster_config.active_members[old_index], new_member, sizeof(raft_member_info_t));
    g_cluster_config.active_members[old_index].status = RAFT_MEMBER_ACTIVE;
    g_cluster_config.active_members[old_index].is_voting_member = true;
    g_cluster_config.active_members[old_index].join_term = raft_cluster_get_term();
    g_cluster_config.active_members[old_index].last_heartbeat_time = get_current_time_ms();
    
    // 如果新成员来自热备列表，从热备列表移除
    int standby_index = find_standby_node_index(new_member->node_id);
    if (standby_index >= 0) {
        for (int i = standby_index; i < g_cluster_config.standby_count - 1; i++) {
            g_cluster_config.standby_nodes[i] = g_cluster_config.standby_nodes[i + 1];
        }
        g_cluster_config.standby_count--;
    }
    
    g_cluster_config.config_version++;
    
    pthread_mutex_unlock(&g_membership_lock);
    
    log_membership_event("MEMBER_REPLACED", old_node_id, "Member replaced");
    
    if (g_change_callback) {
        g_change_callback(RAFT_CONFIG_REPLACE_MEMBER, &old_member, "Member replacement");
        g_change_callback(RAFT_CONFIG_ADD_MEMBER, new_member, "Replacement member added");
    }
    
    return 0;
}

int raft_update_member_health(int node_id, double health_score) {
    if (!g_membership_initialized || health_score < 0.0 || health_score > 1.0) {
        return -1;
    }
    
    pthread_mutex_lock(&g_membership_lock);
    
    // 更新活跃成员健康评分
    int active_index = find_active_member_index(node_id);
    if (active_index >= 0) {
        g_cluster_config.active_members[active_index].health_score = health_score;
        g_cluster_config.active_members[active_index].last_heartbeat_time = get_current_time_ms();
        
        // 如果健康评分提高，重置故障计数
        if (health_score > 0.8) {
            g_cluster_config.active_members[active_index].failure_count = 0;
            if (g_cluster_config.active_members[active_index].status == RAFT_MEMBER_FAILED) {
                g_cluster_config.active_members[active_index].status = RAFT_MEMBER_ACTIVE;
                log_membership_event("MEMBER_RECOVERED", node_id, "Member health restored");
            }
        }
        
        pthread_mutex_unlock(&g_membership_lock);
        return 0;
    }
    
    // 更新热备节点健康评分
    int standby_index = find_standby_node_index(node_id);
    if (standby_index >= 0) {
        g_cluster_config.standby_nodes[standby_index].health_score = health_score;
        g_cluster_config.standby_nodes[standby_index].last_heartbeat_time = get_current_time_ms();
        pthread_mutex_unlock(&g_membership_lock);
        return 0;
    }
    
    pthread_mutex_unlock(&g_membership_lock);
    return -2; // 节点不存在
}

int raft_get_quorum_size(void) {
    if (!g_membership_initialized) {
        return -1;
    }
    
    pthread_mutex_lock(&g_membership_lock);
    int quorum = calculate_quorum_size();
    pthread_mutex_unlock(&g_membership_lock);
    
    return quorum;
}

bool raft_has_majority_votes(int vote_count) {
    int quorum = raft_get_quorum_size();
    return (quorum > 0) && (vote_count >= quorum);
}

int raft_configure_auto_healing(const raft_auto_healing_config_t* config) {
    if (!config || !g_membership_initialized) {
        return -1;
    }
    
    pthread_mutex_lock(&g_membership_lock);
    memcpy(&g_auto_healing_config, config, sizeof(raft_auto_healing_config_t));
    pthread_mutex_unlock(&g_membership_lock);
    
    log_membership_event("CONFIG_UPDATED", -1, "Auto-healing configuration updated");
    return 0;
}

int raft_register_member_change_callback(raft_member_change_callback_t callback) {
    g_change_callback = callback;
    return 0;
}

bool raft_is_in_joint_consensus(void) {
    if (!g_membership_initialized) {
        return false;
    }
    
    pthread_mutex_lock(&g_membership_lock);
    bool in_joint = g_cluster_config.in_joint_consensus;
    pthread_mutex_unlock(&g_membership_lock);
    
    return in_joint;
}

int raft_get_cluster_health_status(void) {
    if (!g_membership_initialized) {
        return -1;
    }
    
    pthread_mutex_lock(&g_membership_lock);
    
    int active_healthy = 0;
    int total_active = g_cluster_config.active_count;
    
    for (int i = 0; i < total_active; i++) {
        if (g_cluster_config.active_members[i].status == RAFT_MEMBER_ACTIVE &&
            g_cluster_config.active_members[i].health_score >= g_auto_healing_config.min_health_score) {
            active_healthy++;
        }
    }
    
    pthread_mutex_unlock(&g_membership_lock);
    
    // 返回健康百分比 (0-100)
    if (total_active == 0) return 0;
    return (active_healthy * 100) / total_active;
}

int raft_get_member_status(int node_id, raft_member_info_t* member_info) {
    if (!member_info || !g_membership_initialized) {
        return -1;
    }
    
    pthread_mutex_lock(&g_membership_lock);
    
    // 查找活跃成员
    int active_index = find_active_member_index(node_id);
    if (active_index >= 0) {
        memcpy(member_info, &g_cluster_config.active_members[active_index], 
               sizeof(raft_member_info_t));
        pthread_mutex_unlock(&g_membership_lock);
        return 0;
    }
    
    // 查找热备节点
    int standby_index = find_standby_node_index(node_id);
    if (standby_index >= 0) {
        memcpy(member_info, &g_cluster_config.standby_nodes[standby_index], 
               sizeof(raft_member_info_t));
        pthread_mutex_unlock(&g_membership_lock);
        return 0;
    }
    
    pthread_mutex_unlock(&g_membership_lock);
    return -2; // 节点不存在
}
